package bar.dark.lee.manager.card;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import bar.dark.lee.R;
import bar.dark.lee.SuperActivity;
import bar.dark.lee.common.BDLog;
import bar.dark.lee.common.BDUtil;
import bar.dark.lee.common.DBSQLite;
import bar.dark.lee.common.DBSQLite.ParseSelectData;
import bar.dark.lee.insert.InsertPostActivity;
import bar.dark.lee.manager.money.BankBookInsertActivity;
import bar.dark.lee.manager.money.BankMoneyActivitiy;
import bar.dark.lee.manager.money.BankbookData;

public class CheckCardAddActivity extends SuperActivity 
	implements OnClickListener, OnItemClickListener
{
/////////////////////////////////////////////////////////////////
///////////////////		위젯 멤버 변수		/////////////////////
/////////////////////////////////////////////////////////////////

	private Button mBtnAdd;
	private Button mBtnCancel;
	private ListView mList;
	private EditText mEditCardName;
	private TextView mTextBankBook;

/////////////////////////////////////////////////////////////////
///////////////////		일반 멤버 변수		/////////////////////
/////////////////////////////////////////////////////////////////

	
	private ArrayList<BankbookData> mArrayBankBook;
	private ArrayAdapter<BankbookData> mAdapterBankBook;
	
	// 그 외
	private DBSQLite sql;
	
	private View resultView;
	
	private int addflag;

/////////////////////////////////////////////////////////////////
///////////////////		오버라이딩 메소드		/////////////////////
/////////////////////////////////////////////////////////////////

	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.setting_checkcard_add_activity);
		
		sql = DBSQLite.getInstance(this);
		
		setTitle("체크카드 추가");
		
		setGoneTipButton();
		
		initWidget();
		initListener();
		
		new ShowDialog().execute(BDUtil.asyncFlag, 1);
	}

	@Override
	public void onClick(View v) 
	{
		if (v == mBtnAdd) 
		{
			if (! (mEditCardName.getText().toString().trim().length() > 0) ) 
			{
				BDUtil.showDialog(CheckCardAddActivity.this, "확인", "이름을 입력해주세요.");
				return;
			} 
			else if (mTextBankBook.getText().toString().equals("")) 
			{
				BDUtil.showDialog(CheckCardAddActivity.this, "확인", "통장을 선택해주세요.");
				return;
			} 
			else 
			{
				boolean nameOverlap = false;
				
				String cardName = mEditCardName.getText().toString().trim();
				nameOverlap = BDUtil.getOverlapCheck(sql, superContext, 
						"select name from check_card where name = '" + BDUtil.getApostrophe(cardName) + "';");
				
				if (nameOverlap) 
				{
					BDUtil.showDialog(CheckCardAddActivity.this, "확인", "동일한 카드 이름이 존재 합니다.");
					return;
				} 
				
				new ShowDialog().execute(BDUtil.asyncFlag, 2);
			}
		} 
		else if (v == mBtnCancel) 
		{
			finish();
		}
	}
	
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) 
	{
		if (mArrayBankBook.size() < 1)
		{
			return;
		}
		
		mTextBankBook.setText(mArrayBankBook.get(arg2).getName());
	}
	
/////////////////////////////////////////////////////////////////
///////////////////			일반 메소드		/////////////////////
/////////////////////////////////////////////////////////////////

	/**
	* 위젯 초기화
	*/
	private void initWidget() {
		mBtnAdd = (Button)findViewById(R.id.SETTING_CHECKCARD_ADD_btnAdd);
		mBtnCancel = (Button)findViewById(R.id.SETTING_CHECKCARD_ADD_btnCancel);
		mList = (ListView)findViewById(R.id.SETTING_CHECKCARD_ADD_listBankBook);
		mEditCardName = (EditText)findViewById(R.id.SETTING_CHECKCARD_ADD_editName);
		mTextBankBook = (TextView)findViewById(R.id.SETTING_CHECKCARD_ADD_textBankbookName);
		resultView = getLayoutInflater().inflate(R.layout.view_no_result, null);
	}
	
	/**
	* 멤버 변수 초기화
	*/
	private void initVariable() 
	{
		if (mList.getFooterViewsCount() > 0)
		{
			mList.removeFooterView(resultView);
		}
		
		if (mArrayBankBook.size() < 1)
		{
			mList.addFooterView(resultView);
			mList.setFooterDividersEnabled(false);
		}
		else
		{
			mList.setFooterDividersEnabled(true);
		}
		
		mAdapterBankBook = new BankBookListAdapter(this, R.layout.list_item_bankbook, mArrayBankBook);
		mList.setAdapter(mAdapterBankBook);
		mAdapterBankBook.notifyDataSetChanged();
		
		if (mArrayBankBook.size() > 0)
		{
			mTextBankBook.setText(mArrayBankBook.get(0).getName());
		}
	}
	
	/**
	* 리스너 초기화
	*/
	private void initListener() 
	{
		mBtnAdd.setOnClickListener(this);
		mBtnCancel.setOnClickListener(this);
		mList.setOnItemClickListener(this);
	}

	/**
	 * 통장 데이터 가져온다
	 */
	private void getBankBookData() 
	{
		mArrayBankBook = new ArrayList<BankbookData>();
		
		sql.selectMapTile(this, "SELECT id, name, money FROM bankbook;", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int count = c.getCount();
				c.moveToFirst();
				
				int idIndex = c.getColumnIndex("id");
				int nameIndex = c.getColumnIndex("name");
				int moneyIndex = c.getColumnIndex("money");
				
				for (int i = 0; i < count; i++)
				{
					BankbookData data = new BankbookData();
					data.setId(c.getString(idIndex));
					data.setName(c.getString(nameIndex));
					data.setMoney(c.getString(moneyIndex));
					
					sql.selectMapTile(superContext, "SELECT addflag FROM bankbook_detail " +
							"WHERE linkid = " + data.getId() + ";", 
							new ParseSelectData()
					{
						@Override
						public void resultData(Cursor c)
						{
							int addflagIdx = c.getColumnIndex("addflag");
							addflag = -1;
							c.moveToFirst();
							
							for (int i = 0; i < c.getCount(); i++)
							{
								addflag = c.getInt(addflagIdx);
								c.moveToNext();
							}
						}
					});
					
					if (addflag == 1)
					{
						data.setFlag("1");
					}
					else
					{
						data.setFlag("0");
					}
					
					mArrayBankBook.add(data);
					
					
					c.moveToNext();
				}
			}
		});
	}

/////////////////////////////////////////////////////////////////
///////////////////			재사용 메소드		/////////////////////
/////////////////////////////////////////////////////////////////




/////////////////////////////////////////////////////////////////
///////////////////			내부 클래스		/////////////////////
/////////////////////////////////////////////////////////////////
	
	/**
	 * 통장 리스트 아답터
	 * @author hyojun
	 *
	 */
	private class BankBookListAdapter extends ArrayAdapter<BankbookData>
	{
		private ArrayList<BankbookData> bankbookList;

		public BankBookListAdapter(Context context, int textViewResourceId,
				ArrayList<BankbookData> list)
		{
			super(context, textViewResourceId, list);
			bankbookList = list;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			View v  = convertView;
			if (v == null)
			{
				LayoutInflater li = (LayoutInflater) getContext().getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
				v = li.inflate(R.layout.list_item_bankbook, null);
			}
			
			BankbookData data = bankbookList.get(position);
			TextView name = (TextView) v.findViewById(R.id.bankbookName);
			TextView money = (TextView) v.findViewById(R.id.bankbookMoney);
			TextView flag = (TextView) v.findViewById(R.id.bankbookFlag);
			
			name.setText(data.getName());
			money.setText(BDUtil.getWon(data.getMoney()) + shape);
			
			if (data.getFlag().equals("0"))
			{
				flag.setTextColor(getResources().getColor(R.color.inmoney));
				flag.setText("자산포함");
			}
			else
			{
				flag.setTextColor(getResources().getColor(R.color.outmoney));
				flag.setText("미포함");
			}
			
			return v;
		}
	}
	
	private void setInsertData()
	{
		sql.selectMapTile(this, "SELECT id FROM bankbook WHERE name = '"
				+ BDUtil.getApostrophe(mTextBankBook.getText().toString()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int idIdx = c.getColumnIndex("id");
				
				c.moveToFirst();
				int id = -1;
				
				for (int i = 0; i < c.getCount(); i++)
				{
					id = c.getInt(idIdx);
					c.moveToNext();
				}
				
				if (id > -1)
				{
					HashMap<String, String> map = new HashMap<String, String>();
					map.put("name", mEditCardName.getText().toString().trim());
					map.put("banklink", id + "");
					sql.insert(superContext, map, "check_card");
				}
			}
		});
		
		sql.selectMapTile(superContext, "SELECT id FROM check_card WHERE name = '"
				+ BDUtil.getApostrophe(mEditCardName.getText().toString()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int idIdx = c.getColumnIndex("id");
				
				int id = -1;
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					id = c.getInt(idIdx);
					c.moveToNext();
				}
				
				if (id > -1)
				{
					HashMap<String, String> map = new HashMap<String, String>();
					map.put("name", mEditCardName.getText().toString());
					map.put("linkid", id + "");
					map.put("count", "999");
					
					// 세부 체크카드 테이블에 데이터를 셋팅한디.
					sql.insert(superContext, map, "checkcard_detail");
				}
			}
		});
	}
	
	/**
	 * 다이얼로그 뛰우기 
	 */
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>{
		ProgressDialog dialog = null;
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			
			if (BDUtil.btnEnable)
			{
				BDUtil.btnEnable = false;
				BDUtil.asyncFlag = -1;
				
				dialog = new ProgressDialog(CheckCardAddActivity.this);
				dialog.setCancelable(false);
				dialog.setMessage("Loading...");
				dialog.show();
			}
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) {
			
			if (arg0[0] == 0) 
			{
				if (arg0[1] == 1)
				{
					getBankBookData();
					
					return arg0[1];
				}
				else if (arg0[1] == 2)
				{
					try
					{
						sql.beginTansaction(superContext);
						
						setInsertData();
						
						sql.setTransactionSuccessful();
					} catch (Exception e)
					{
						return -1;
					} finally {
						try 
						{
							sql.endTransaction(superContext);
						} catch (Exception e) 
						{
							return -1;
						}
					}
					
					return arg0[1];
				}
				return arg0[0];
			} else 
				return arg0[0];
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			
			if (dialog != null) {
				dialog.dismiss();
			}
			
			if (result == -1)
			{
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
				
				BDUtil.showDialog(superContext, "오류", "데이터 저장에 실패했습니다.");
			}
			else if (result == 1) 
			{
				initVariable();
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
			} 
			else if (result == 2) 
			{
				BDUtil.showDialogFinish(CheckCardAddActivity.this, "확인", "체크카드가 추가 되었습니다.");
			}
		}
	}

	@Override
	protected void tipButton()
	{
	}
}
